home *** CD-ROM | disk | FTP | other *** search
- Path: solon.com!not-for-mail
- From: rastrl@cs.buffalo.edu (Robert L Rast)
- Newsgroups: comp.lang.c,comp.lang.c.moderated
- Subject: Re: Leading and Trailing Blanks
- Date: 5 Jan 1996 09:54:04 -0600
- Organization: State University of New York at Buffalo/Computer Science
- Sender: clc@solutions.solon.com
- Approved: clc@solutions.solon.com
- Message-ID: <4cjhis$fb1@solutions.solon.com>
- References: <4chh1b$685@solutions.solon.com>
- NNTP-Posting-Host: solutions.solon.com
-
-
- In article <4chh1b$685@solutions.solon.com>,
- Casey Claiborne <mskc@io.com> wrote:
- >
- >
- >Hello -
- > I am wondering if anyone out there has a program (or knows of one)
- >that allows one to strip leading and trailing blanks from a string.
- >ex:
- >
- > char test[20];
- > strcpy(test," TESTING ");
- > printf("%s", test);
- >
- >will produce an output like
- > TESTING
- >
- >that has blanks at the beginning of "TESTING". I would like to
- >have the following result
- >
- >TESTING
- >
- >that has no leading blanks.
- >
-
-
- This might work:
-
-
-
- #include <stdio.h>
- #include <string.h>
-
- char * tstr = " TESTING ";
- char * strip (char * dest, char * src);
-
-
- int main (void) {
-
- char result[256];
-
- strip(result, tstr);
- printf("tstr=%s.\t length = %d\n", tstr, strlen(tstr));
- printf("result=%s.\t length = %d\n", result, strlen(result));
- return 0;
- }
- }
-
-
-
- char * strip (char * dest, char * src) {
-
- char * fptr, * bptr; /* front and back ptrs */
-
- if (NULL == src || '\0' == *src) {
- *dest = '\0';
- return src;
- }
- fptr = src;
- bptr = src + strlen(src) - 1;
- while(' ' == *fptr && '\0' != *fptr) ++fptr;
- while(' ' == *bptr && bptr > src) --bptr;
- if (bptr >= fptr) {
- int len = 1 + (bptr-fptr);
- strncpy(dest, fptr, len);
- *(dest + len) = '\0';
- }
- else
- *dest = '\0';
- return dest;
- }
- }
-
- /* end */
-
-
-
- It was tested with null and zero-length strings. Also, a string with
-
- all spaces succeeded. You could probably substitute "isspace(*ptr)" for
-
- the ' ' condition in the while loops - this will take care of tabs, etc.
-
- Hope you like it, it's all I got.
-
-
- Psychovoid 2007
-
-
- "Just because it's bad doesn't mean it won't be popular. After
- all, it's Microsoft." ___
- __ (.x.) __
- --rastrl@acsu.buffalo.edu--(,,^\--\-/--/^,,)--www.acsu.buffalo.edu/~rastrl--
-
-
-
-